package fdoj.eventInvitations.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.Properties;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMail {
	private ResourceBundle resourceBundle;
	public void Send(String email, String text, String subject){
	   
	    try {
			Locale l = Locale.getDefault();
			String path = "/properties/email.properties";

			Reader reader;
			InputStream stream=getClass().getResourceAsStream(path);
			InputStreamReader inputStreamReader=new InputStreamReader(stream, "utf-8");
			reader = new BufferedReader(inputStreamReader);
			resourceBundle = new PropertyResourceBundle(reader);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String host = resourceBundle.getString("host");
	    String userid = resourceBundle.getString("userid");
	    String password = resourceBundle.getString("password");
	    try {
         Properties props = new Properties();
         props.setProperty("mail.host", host);
         props.setProperty("mail.smtp.port", "587");
         props.setProperty("mail.smtp.auth", "true");
         props.setProperty("mail.smtp.starttls.enable", "true");

         Authenticator auth = new SMTPAuthenticator(userid, password);

         Session session = Session.getInstance(props, auth);

         MimeMessage msg = new MimeMessage(session);
         msg.setText(text);
         msg.setSubject(subject);
       
         msg.setFrom(new InternetAddress(userid));
         msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
         Transport.send(msg);

     } catch (Exception e) {
       e.printStackTrace();

     }
	}
     private class SMTPAuthenticator extends Authenticator {

	        private PasswordAuthentication authentication;

	        public SMTPAuthenticator(String login, String password) {
	            authentication = new PasswordAuthentication(login, password);
	        }

	        protected PasswordAuthentication getPasswordAuthentication() {
	            return authentication;
	        }
	    }
}
